package chpt09;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

class CallableCounter implements Callable<Integer> {
	private Integer n;
	public CallableCounter(Integer n) {
		this.n = n;
	}

	@Override
	public Integer call() throws Exception {
		int result = 0;
		for (int i = 0; i < n; i++) {
			result += i;
			Thread.sleep(500);
		}
		return result;
	}

}

public class CallableTest {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		int n = 10;
		Callable<Integer> callableTask = new CallableCounter(n);
		FutureTask<Integer> futureTask = new FutureTask<>(callableTask);
		Thread thread = new Thread(futureTask);
		thread.start();
		System.out.println("futureTask正在运行...");
		Integer result = futureTask.get(); // 阻塞，直到线程运行结束
		System.out.println("callableTask运行结果为" + result);
	}
}
